package com.hehao.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    public static final String QUEUE_1 = "topicQueue1";
    public static final String QUEUE_2 = "topicQueue2";
    public static final String QUEUE_3 = "topicQueue3";
    public static final String EXCHANGE = "testTopicExchange";
    public static final String ROUTING_KEY_1 = "topic.*";
    public static final String ROUTING_KEY_2 = "topic.#";
    public static final String ROUTING_KEY_3 = "topic.y.#";

    @Bean
    public Queue queueA() {
        return new Queue(QUEUE_1, false);
    }

    @Bean
    public Queue queueB() {
        return new Queue(QUEUE_2, false);
    }

    @Bean
    public Queue queueC() {
        return new Queue(QUEUE_3, false);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(EXCHANGE);
    }

    @Bean
    public Binding bindingA() {
        return BindingBuilder.bind(queueA()).to(exchange()).with(ROUTING_KEY_1);
    }

    @Bean
    public Binding bindingB() {
        return BindingBuilder.bind(queueB()).to(exchange()).with(ROUTING_KEY_2);
    }

    @Bean
    public Binding bindingC() {
        return BindingBuilder.bind(queueB()).to(exchange()).with(ROUTING_KEY_3);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean(name = "myRabbitMQ")
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}